package com.qf.shopping.utils;
import com.qf.shopping.dto.Email;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**调用jar简单的封装了发送邮件的方法
 * @author 三旬
 * @version 1.0  2022/9/21
 */
public class SendEmail {

//    public static void main(String[] args) throws Exception {
//
//        Email email = new Email();
//        email.setToUser("1925675524@qq.com");
//        email.setTitle("2205电商项目新用户激活");
//        email.setContent("欢迎成为我们系统的会员，<a href ='http://localhost:8080/SSOController/acitveUser?code=123456'>点击这里激活</a>");
//        email.setCcUser("liyingwen1030@163.com");
//        sendEmailInfoUser(email);
//        System.out.println("邮件发送成功！");
//    }
//


    public static void sendEmailInfoUser(Email email) throws Exception {
        Properties properties = new Properties();
        //设置服务器名称
        properties.setProperty("mail.host", "smtp.163.com");

        //设置邮件传输协议
        properties.setProperty("mail.transport.protocol", "smtp");

        //设置是否要验证服务器用户名和密码
        properties.setProperty("mail.smtp.auth", "true");

        // 1.创建客户端与邮箱服务器的Session对象
        Session session = Session.getInstance(properties);

        // 2.开启session的debug模式，方便查看发送email的运行状态
        session.setDebug(true);

        // 3.通过session得到transport传输对象
        Transport transport = session.getTransport();

        // 4.使用用户名密码连接上邮箱服务器,此处的密码需要到邮箱开启服务设置
        //host:SMTP服务器
        //user:用户名（发件人）
        //password:邮箱开启开发者模式设置的密码
        transport.connect("smtp.163.com", "liyingwen1030@163.com", "KVVWYCXIYGCKAESF");

        // 5.创建邮件
        Message message = createSimpleMail(session, email);

        // 6.发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    private static Message createSimpleMail(Session session, Email email) throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("liyingwen1030@163.com"));
        // 指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email.getToUser()));
        // 邮件的标题
        message.setSubject(email.getTitle());
        // 邮件的内容
        message.setContent(email.getContent(), "text/html;charset=UTF-8");

        // 设置抄送人
        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(email.getToUser()));

        return message;
    }

}
